<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>碰撞</title>
		<style type="text/css">
			#div1{width: 100px; height: 100px; background-color: blue; position: absolute; left: 100px; top: 100px;}
			#div2{width: 100px; height: 100px; background-color: red; position: absolute; left: 300px; top: 70px;}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				var oDiv1 = document.getElementById("div1");
				var oDiv2 = document.getElementById("div2");
				
				oDiv2.onmousedown = function(ev){
					var e = ev || window.event;
					
					var offsetX = e.clientX - oDiv2.offsetLeft;
					var offsetY = e.clientY - oDiv2.offsetTop;
					
					document.onmousemove = function(ev){
						var e = ev || window.event;
						
						if(knockBrick(oDiv1, oDiv2)){
							oDiv1.style.backgroundColor = "black";
						}
						else{
							oDiv1.style.backgroundColor = "blue";
						}
						
						oDiv2.style.left = e.clientX - offsetX + "px";
						oDiv2.style.top = e.clientY - offsetY + "px";
					}
					
					document.onmouseup = function(){
						document.onmousemove = null;
					}
				}
			}
			
			//碰撞检查
			function knockBrick(node1, node2){
				var l1 = node1.offsetLeft;
				var r1 = node1.offsetLeft + node1.offsetWidth;
				var t1 = node1.offsetTop;
				var b1 = node1.offsetTop + node1.offsetHeight;
				
				var l2 = node2.offsetLeft;
				var r2 = node2.offsetLeft + node2.offsetWidth;
				var t2 = node2.offsetTop;
				var b2 = node2.offsetTop + node2.offsetHeight;
				
				if((l2 > r1) || (r2 < l1) || (t2 > b1) || (b2 < t1)){
					return false;
				}
				else{
					return true;
				}
			}
		</script>
	</head>
	<body>
		<div id="div1"></div>
		<div id="div2"></div>
	</body>
</html>
